<?php
namespace app\api\model;
use think\Cache;
use controller\Easemob;

class User extends Common
{
    /**
     * 用户注册
     */
    public function register($data)
    {
        $name = $data['name'];
        $mobile  = $data['mobile'];

        $user = $this->where('mobile',$mobile)->find();
        if($user) {return 500;}; 
        $user = $this->where('name',$name)->find();
        if($user) {return 501;}; 
        $h = new Easemob();
        $hx_username = strtolower(GetfourStr(4)."_".substr($mobile,-4));
        $hx_password = substr($mobile,-6);
        $hx_user = $h->getUser($hx_username);
        $h->createUser($hx_username,$hx_password);
        $options = array(
            'groupname'=>$name,
            'desc'=>$name.'群信息',
            'owner'=>$hx_username,
            'public'=>true,
            'approval'=>false,
        );
        $data['hx_username'] = $hx_username;
        $data['hx_password'] = $hx_password;
        $data['hx_groupid']  = $h->createGroup($options);

        if($this->data($data)->allowField(true)->save() !== false)return 0;

        return 503;
    }

    /**
     * 用户登录认证
     */
    public function login($mobile, $password){
        $map['mobile'] = $mobile;
        /* 获取用户数据 */
        $user = $this->where($map)->find();

        if($user){
            /* 验证用户密码 */
            if($password==Cache::get($mobile))
            {
                // 生成 token
                $token = buildToken($user->name);
                Cache::set(config('tokenPrefix') . $token, $user->id, config('token_expires'));
                $data = [
                    'token' => $token,
                    'role'  => $user['role'],
                    'hx_username' => $user['hx_username'],
                    'hx_password' => $user['hx_password']
                ];
                if($user['role'] == 1)
                {
                    $data['hx_groupid'] = $user['hx_groupid'];
                }
                return $data; //登录成功，返回用户ID
            } 
            else 
            {
                return 0; //密码错误
            }
        }
        else 
        {
            return 0; //用户不存在或被禁用
        }
    }

    public function logout()
    {
        cache(config('tokenPrefix').$this->token, NULL);
        cache(config('tokenAndUserPrefix') . $user['id'], NULL);
    }

    public function getUserInfo($token)
    {
        $user_id = Cache::get(config('tokenPrefix') . $token);

        if ($user_id == false) return false;

        $user = $this->where('id',$user_id)->find();
        
        return $user;
    }

}